package jmine.tec.publisher;

import java.util.HashMap;

import jmine.tec.subscription.PublicationListener;
import jmine.tec.subscription.Publisher;
import jmine.tec.subscription.PublisherManager;
import jmine.tec.subscription.SubscriptionManager;
import jmine.tec.subscription.SubscriptionSet;
import jmine.tec.subscription.SubscriptionSettings;

import org.springframework.beans.factory.InitializingBean;

public class SimplePublicationListener implements PublicationListener<SimplePublication>, InitializingBean {

    private SubscriptionManager subscriptionManager;

    private PublisherManager publisherManager;

    public boolean isTransactionRequired() {
        return false;
    }

    /**
     * @param subscriptionManager the subscriptionManager to set
     */
    public void setSubscriptionManager(SubscriptionManager subscriptionManager) {
        this.subscriptionManager = subscriptionManager;
    }

    /**
     * @param publisherManager the publisherManager to set
     */
    public void setPublisherManager(PublisherManager publisherManager) {
        this.publisherManager = publisherManager;
    }

    @SuppressWarnings("unchecked")
    public void afterPropertiesSet() throws Exception {
        SubscriptionSet set = this.subscriptionManager.newSubscription();
        final Publisher<SimplePublication> publisher = (Publisher<SimplePublication>) this.publisherManager.getPublisher("simplePublisher");
        final SubscriptionSettings settings = publisher.newSubscriptionSettings(new HashMap<String, Object>());
        this.subscriptionManager.addSubscription(set, publisher, settings, this);
    }

    public void onPublication(Publisher<SimplePublication> publisher, SubscriptionSettings settings, SimplePublication publication) {
        System.out.println("msg received: " + publication.getText());
    }

    /**
     * {@inheritDoc}
     */
    public boolean isAssynchronous() {
        return true;
    }

}
